package download;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import settings.Settings;

public class YoutubeDownload extends Download
{

	protected String forcedExtension = "";
	protected YoutubeDownload(URL url)
	{
		super(url);
	}
	
	@Override
	public void run()
	{
		super.run();
	}
	
	@Override
	protected void getFileName(URL url, HttpURLConnection connection) throws MalformedURLException, IOException
	{
		file = url.getFile();// nom de fichier
		System.out.println(connection.getResponseCode());
		while ((connection.getResponseCode() >= 300 && connection
				.getResponseCode() < 400)
				|| connection.getResponseCode() == 201)// tant qu'on est
														// redirige
		{
			String s = connection.getHeaderField("Location");
			URL u = null;
			System.out.println("Location " + s);
			if (s.startsWith("http://") || s.startsWith("https://"))
				u = new URL(s);
			else
				u = new URL(url.getProtocol(), url.getHost(), s);

			url = u;
			connection = (HttpURLConnection) url.openConnection();
			connection.connect();
			file = url.getFile();

		}
		int index = file.lastIndexOf("id=")+3;
		file = file.substring(index);
		String temp = Settings.get("path");
		if (!temp.endsWith("\\"))
			temp += "\\";
		if(forcedExtension.isEmpty())
			path = temp+file+".flv";
		else
			path = temp+file+((forcedExtension.startsWith(".")?forcedExtension:"."+forcedExtension));
			
	}

	public String getForcedExtension()
	{
		return forcedExtension;
	}

	public void setForcedExtension(String forcedExtension)
	{
		this.forcedExtension = forcedExtension;
	}
	


}
